<template>
    <div class="register-container">
      <el-card class="register-card">
        <div class="register-header">
          <h2>注册账号</h2>
        </div>
  
        <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
          <el-form-item prop="username">
            <el-input 
              v-model="registerForm.username" 
              placeholder="用户名" 
              prefix-icon="User"
            />
          </el-form-item>
  
          <el-form-item prop="password">
            <el-input 
              v-model="registerForm.password" 
              type="password" 
              placeholder="密码" 
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
  
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="handleRegister" 
              style="width: 100%"
            >
              注册
            </el-button>
          </el-form-item>
  
          <el-form-item>
            <el-button 
              type="text" 
              @click="goToLogin" 
              style="width: 100%; text-align: center"
            >
              已有账号？点击登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { authApi } from '../api/auth'
  
  const router = useRouter()
  const registerFormRef = ref(null)
  const loading = ref(false)
  
  const registerForm = reactive({
    username: '',
    password: ''
  })
  
  const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }
  
  const handleRegister = async () => {
    if (!registerFormRef.value) return
  
    try {
      await registerFormRef.value.validate()
      loading.value = true
  
      const response = await authApi.register(registerForm.username, registerForm.password)
      const { message } = response.data
  
      ElMessage.success(message || '注册成功')
      router.push('/login') // 跳转到登录页面
    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error(error.response?.data?.message || '注册失败，请稍后再试')
    } finally {
      loading.value = false
    }
  }
  
  const goToLogin = () => {
    router.push('/login')
  }
  </script>
  
  <style scoped>
  .register-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
  }
  
  .register-card {
    width: 350px;
  }
  
  .register-header {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .register-header h2 {
    margin-bottom: 8px;
    color: #409EFF;
  }
  </style>